package com.shoujifeng.snowmusic.player;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.geniuseoe2012.lazyloaderdemo.cache.ImageLoader;
import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.utils.SlideSwitch;
import com.shoujifeng.snowmusic.player.utils.SlideSwitch.OnSwitchChangedListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.net.Uri;

public class setActivity extends Activity {
	private RelativeLayout headView;
	private RelativeLayout setStopLay;
	private TextView headText;
	private ImageButton breakBtn;
	private RelativeLayout loginLay;
	private RelativeLayout ideaLay;
	private RelativeLayout aboutLay;
	private RelativeLayout checkLay;
	private RelativeLayout markLay;
	private TextView loginTxt;
	private TextView userNameTxt;
	private TextView musicStopTimeTxt;
	// 底部的软件推荐
	private ImageView setBottomImg1;
	private ImageView setBottomImg2;
	private ImageView setBottomImg3;
	private ImageView setBottomImg4;
	private com.shoujifeng.snowmusic.player.utils.SlideSwitch wifiSwitch;
	private com.shoujifeng.snowmusic.player.utils.SlideSwitch messageSendSwitch;
	private SharedPreferences spf;
	private final int UPDATE_DATA = 0;
	private Thread accThread;
	private ServerAccess serverAccess;
	private ArrayList<HashMap<String, Object>> mAppList;
	private ImageLoader mImageLoader;
	
	private HashMap<String, Object> mAppMap;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_layout);
		init();
		initGlobalValue();
		accThread = new Thread(runnable);
		accThread.start();
	}
	
	
	@Override
	protected void onResume() {

		if(ServerAccess.uid <= 0) {
			if(loginTxt != null) {
				loginTxt.setText("登陆");
				userNameTxt.setText("");
			}
		}
		
		super.onResume();
	}


	private void init() {
		spf = PreferenceManager.getDefaultSharedPreferences(setActivity.this);
		serverAccess = new ServerAccess(setActivity.this);
		mImageLoader = new ImageLoader(setActivity.this);

		headView = (RelativeLayout) findViewById(R.id.headLay);
		headText = (TextView) headView.findViewById(R.id.head_text);
		breakBtn = (ImageButton) headView.findViewById(R.id.breakBtn);
		musicStopTimeTxt = (TextView) findViewById(R.id.musicStopTimeTxt);
		setLastStopTime();
		loginLay = (RelativeLayout) findViewById(R.id.loginLay);
		wifiSwitch = (SlideSwitch) findViewById(R.id.wifiSwitch);
		messageSendSwitch = (SlideSwitch) findViewById(R.id.messageSendSwitch);
		setStopLay = (RelativeLayout) findViewById(R.id.set_stop_lay);
		aboutLay = (RelativeLayout) findViewById(R.id.set_about_layout);
		checkLay = (RelativeLayout) findViewById(R.id.check_version);
		markLay = (RelativeLayout) findViewById(R.id.mark_lay);
		setBottomImg1 = (ImageView) findViewById(R.id.setBottomImg1);
		setBottomImg2 = (ImageView) findViewById(R.id.setBottomImg2);
		setBottomImg3 = (ImageView) findViewById(R.id.setBottomImg3);
		setBottomImg4 = (ImageView) findViewById(R.id.setBottomImg4);
		setBottomImg1.setOnClickListener(onClickListener);
		setBottomImg2.setOnClickListener(onClickListener);
		setBottomImg3.setOnClickListener(onClickListener);
		setBottomImg4.setOnClickListener(onClickListener);

		headText.setText("设置");
		breakBtn.setOnClickListener(onClickListener);
		setStopLay.setOnClickListener(onClickListener);
		aboutLay.setOnClickListener(onClickListener);
		checkLay.setOnClickListener(onClickListener);
		markLay.setOnClickListener(onClickListener);

		String value = spf.getString(ServerAccess.SET_WIFI, "no");
		if (value.equals("yes")) {
			wifiSwitch.setStatus(true);
		}
		
		value = spf.getString(ServerAccess.PUSH, "no");
		if (value.equals("yes")) {
			messageSendSwitch.setStatus(true);
		}

		wifiSwitch.setOnSwitchChangedListener(new OnSwitchChangedListener() {
			@Override
			public void onSwitchChanged(SlideSwitch obj, int status) {
				// TODO Auto-generated method stub
				if (status == 0) {
					// 写入数据到配置文件中 关闭状态
					spf = PreferenceManager
							.getDefaultSharedPreferences(setActivity.this);
					Editor edit = spf.edit();
					edit.putString(ServerAccess.SET_WIFI, "no");
					edit.commit();
				}
				if (status == 1) { // 打开状态
					spf = PreferenceManager
							.getDefaultSharedPreferences(setActivity.this);
					Editor edit = spf.edit();
					edit.putString(ServerAccess.SET_WIFI, "yes");
					edit.commit();
				}
			}
		});
		
		messageSendSwitch.setOnSwitchChangedListener(new OnSwitchChangedListener() {
			@Override
			public void onSwitchChanged(SlideSwitch obj, int status) {
				// TODO Auto-generated method stub
				if (status == 0) {
					// 写入数据到配置文件中 关闭状态
					spf = PreferenceManager
							.getDefaultSharedPreferences(setActivity.this);
					Editor edit = spf.edit();
					edit.putString(ServerAccess.PUSH, "no");
					edit.commit();
					
					Toast.makeText(setActivity.this, "已关闭推送, 下次生效!", Toast.LENGTH_SHORT).show();
				}
				else if (status == 1) { // 打开状态
					spf = PreferenceManager
							.getDefaultSharedPreferences(setActivity.this);
					Editor edit = spf.edit();
					edit.putString(ServerAccess.PUSH, "yes");
					edit.commit();
					
					Toast.makeText(setActivity.this, "已开启推送, 下次生效!", Toast.LENGTH_SHORT).show();
				}
				
				 
			}
		});

		loginLay.setOnClickListener(onClickListener);
		ideaLay = (RelativeLayout) findViewById(R.id.ideaLay);
		ideaLay.setOnClickListener(onClickListener);

		loginTxt = (TextView) findViewById(R.id.loginTxt);
		userNameTxt = (TextView) findViewById(R.id.userNameTxt);
		String code = spf.getString(ServerAccess.CODE, "");
		String nickName = spf.getString(ServerAccess.NICKNAME, "");
		if (code.equals("1")) {
			loginTxt.setText("退出账号");
		} else {
			loginTxt.setText("登陆");
		}
		if (code.equals("1")) {
			userNameTxt.setText(nickName);
		} else {
			userNameTxt.setText("");
		}

	}

	private View.OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.breakBtn: {
				finish();
				overridePendingTransition(R.anim.no_move, R.anim.right_out);
			}
				break;
			case R.id.loginLay: {
				if (spf.getString(ServerAccess.CODE, "").equals("1")) {
					Intent intent = new Intent(setActivity.this,
							LoginOutActivity.class);
					startActivity(intent);

				} else {
					Intent intent = new Intent(setActivity.this,
							LoginActivity.class);
					startActivity(intent);

				}
				
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
				break;
			case R.id.ideaLay: {
				Intent intent = new Intent(setActivity.this, IdeaActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
				break;
			case R.id.check_version:
			{
				getAppMark(0);
			}
				break;
			case R.id.mark_lay:
			{
				getAppMark(1);
			}
				break;
			case R.id.set_stop_lay: {
				// Intent intent = new Intent(setActivity.this,
				// SetStopTimeActivity.class);
				// startActivity(intent);
				new AlertDialog.Builder(setActivity.this)
						.setTitle("选择定时时间")
						.setItems(
								new String[] { "10分钟", "20分钟", "30分钟", "60分钟",
										"90分钟", "关闭定时" },
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										// TODO Auto-generated method stub
										if (arg1 == 0) {
											setStopTime(10);
										}

										if (arg1 == 1) {
											setStopTime(20);
										}

										if (arg1 == 2) {
											setStopTime(30);
										}

										if (arg1 == 3) {
											setStopTime(60);
										}

										if (arg1 == 4) {
											setStopTime(90);
										}

										if (arg1 == 5) {
											setStopTime(0);
										}

									}
								}).setNegativeButton("确定", null).show();

			}
				break;
			case R.id.set_about_layout: {
				Intent intent = new Intent(setActivity.this,
						AboutActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
				break;
			case R.id.setBottomImg1: {
				Intent intent= new Intent();        
			    intent.setAction("android.intent.action.VIEW");    
			    Uri content_url = Uri.parse(mAppList.get(0).get(ServerAccess.URL).toString());   
			    intent.setData(content_url);  
			    startActivity(intent);
				
			}
				break;
			case R.id.setBottomImg2: {
				Intent intent= new Intent();        
			    intent.setAction("android.intent.action.VIEW");    
			    Uri content_url = Uri.parse(mAppList.get(1).get(ServerAccess.URL).toString());   
			    intent.setData(content_url);  
			    startActivity(intent);
			}
				break;
			case R.id.setBottomImg3: {
				Intent intent= new Intent();        
			    intent.setAction("android.intent.action.VIEW");    
			    Uri content_url = Uri.parse(mAppList.get(2).get(ServerAccess.URL).toString());   
			    intent.setData(content_url);  
			    startActivity(intent);
			}
				break;
			case R.id.setBottomImg4: {
				Intent intent= new Intent();        
			    intent.setAction("android.intent.action.VIEW");    
			    Uri content_url = Uri.parse(mAppList.get(3).get(ServerAccess.URL).toString());   
			    intent.setData(content_url);  
			    startActivity(intent);
			}
				break;
			
			default:
				break;
			}

		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		{
			finish();
			
			overridePendingTransition(R.anim.no_move, R.anim.right_out);
		}
			break;

		default:
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	private void getAppMark(final int type) {
		new AsyncTask<Integer, Integer, Integer>() {

			@Override
			protected Integer doInBackground(Integer... params) {
				
				try {
					ArrayList<HashMap<String, Object>> array = serverAccess.getAppMsg(new String[]{"version", "content", "appstore"});
					
					mAppMap = array.get(0);
					
					publishProgress(0);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				return null;
			}

			@Override
			protected void onProgressUpdate(Integer... values) {
				if(type == 0) {
					float version = Float.parseFloat(mAppMap.get("version").toString());
					
					if(GlobalValue.VERSION < version)
					{
						new AlertDialog.Builder(setActivity.this) 
						.setTitle("发现新版本!")
						.setMessage(mAppMap.get("content").toString())
						.setPositiveButton("更新", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								Uri uri = Uri.parse(mAppMap.get("appstore").toString());  
								Intent intent = new Intent(Intent.ACTION_VIEW,uri);  
								intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
								startActivity(intent);  
							}
						})
						.setNegativeButton("取消", null)
						.show();
					}
				}
				else {
					Uri uri = Uri.parse(mAppMap.get("appstore").toString());  
					Intent intent = new Intent(Intent.ACTION_VIEW,uri);  
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
					startActivity(intent);  
				}
				super.onProgressUpdate(values);
			}
			
			
		}.execute(0);
	}

	private void setStopTime(int time) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String nowTime = formatter.format(new Date());

		SharedPreferences spf = PreferenceManager
				.getDefaultSharedPreferences(setActivity.this);
		Editor edit = spf.edit();
		edit.putString(ServerAccess.SET_STOP_TIME, Integer.toString(time));
		edit.putString(ServerAccess.SET_TIME, nowTime);
		edit.commit();
		setLastStopTime();
		if(time==0){
			Toast.makeText(setActivity.this, "关闭定时",
					Toast.LENGTH_SHORT).show();
		}
		else{
			Toast.makeText(setActivity.this, "播放器" + time + "分钟后停止!",
					Toast.LENGTH_SHORT).show();
		}
		
	}

	private void setLastStopTime() {
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String nowTime = sd.format(new Date());
		String setTime = spf.getString(ServerAccess.SET_TIME, "");
		String setStopTime = spf.getString(ServerAccess.SET_STOP_TIME, "");
		long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
		long nh = 1000 * 60 * 60;// 一小时的毫秒数
		long nm = 1000 * 60;// 一分钟的毫秒数
		long ns = 1000;// 一秒钟的毫秒数
		long diff;
		long min = 0;

		try {
			diff = sd.parse(nowTime).getTime() - sd.parse(setTime).getTime();
			min = diff % nd % nh / nm;// 计算差多少分钟
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (!setTime.equals("") && Long.parseLong(setStopTime) - min > 0) {
			musicStopTimeTxt.setText(Long.parseLong(setStopTime) - min
					+ "分钟后停止");
		} else {
			musicStopTimeTxt.setText("");
		}
	}

	protected Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_DATA: {
				mImageLoader.DisplayImage(
						mAppList.get(0).get(ServerAccess.ICON_URL).toString(),
						setBottomImg1, false, R.drawable.setimg1);
				mImageLoader.DisplayImage(
						mAppList.get(1).get(ServerAccess.ICON_URL).toString(),
						setBottomImg2, false, R.drawable.setimg1);
				mImageLoader.DisplayImage(
						mAppList.get(2).get(ServerAccess.ICON_URL).toString(),
						setBottomImg3, false, R.drawable.setimg1);
				mImageLoader.DisplayImage(
						mAppList.get(3).get(ServerAccess.ICON_URL).toString(),
						setBottomImg4, false, R.drawable.setimg1);
			}
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				String[] keys = new String[] { ServerAccess.ID,
						ServerAccess.MUSIC_NAME, ServerAccess.URL,
						ServerAccess.ICON_URL, ServerAccess.CODE };
				mAppList = new ArrayList<HashMap<String, Object>>();
				mAppList = serverAccess.getAppList(keys);
				sendMessage(UPDATE_DATA);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	private void initGlobalValue() {
		GlobalValue.initSDAddr();

		GlobalValue.addUrl(ServerAccess.APP_LIST,
				"http://www.snowmusic.com.cn/mobile_api/app_list.php");
	}
}
